package io.kimmking.rpcfx.register.center.redis;

import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.register.center.api.ProviderInfo;
import io.kimmking.rpcfx.register.center.api.Register;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.*;


/**
 * @author lfy
 */
public class RedisRegister implements Register {
//    public static void main(String[] args) {
//        RedisRegister redisRegister = new RedisRegister("127.0.0.1",6379,"test_register");
//        redisRegister.register(ProviderInfo.builder().host("192.168.1.5").port(8080).serviceName("io.kimmking.rpcfx.demo.api.OrderService").build());
//        redisRegister.register(ProviderInfo.builder().host("192.168.1.5").port(8080).serviceName("io.kimmking.rpcfx.demo.api.OrderService2").build());
//    }
    private final long timeout=10;
    private final JedisPool jedisPool;
    private final String namespace;
    ScheduledExecutorService scheduledThreadPool;
    private final String host;
    private final int port;
    public RedisRegister(String host,int port, String namespace) {
        System.out.println("init RedisRegister");
        this.host = host;
        this.port = port;
        jedisPool = new JedisPool(host,port);
        this.namespace = namespace;
        scheduledThreadPool = Executors.newScheduledThreadPool(1);
    }

    @Override
    public void register(ProviderInfo providerInfo) {
        String serviceName = providerInfo.getServiceName();
        try {
            String key = namespace+":" +serviceName+":"+generateNodeName(providerInfo,serviceName);
            String providerStr = JSON.toJSONString(providerInfo);
            scheduledThreadPool.scheduleAtFixedRate(()->{
                try  {
                    Jedis jedis = jedisPool.getResource();
                    jedis.setex(key,(int)timeout,providerStr);

                    //jedis.set(key,providerStr,SetParams.setParams().ex(timeout));
                    //jedis.set(key,providerStr);
                    jedis.close();
                    System.out.println("Register续约redis完成:"+key);
                }catch (Exception ex){
                    System.out.println("续约出现异常");
                    ex.printStackTrace();
                }
            },0,5,TimeUnit.SECONDS);

        }catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }


    }


    private String generateNodeName(ProviderInfo providerInfo, String serviceName) {
        return providerInfo.getHost() + ":" + providerInfo.getPort();
    }

}
